package com.wanpinghui.supplier.common;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.githang.statusbar.StatusBarCompat;
import com.umeng.analytics.MobclickAgent;
import com.wanpinghui.supplier.Config;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.StartActivity;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.oauth.LoginActivity;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.supplier.object.ObjectDetailActivity;
import com.wanpinghui.supplier.widgets.TopWarningTextView;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.GrobalListener;
import com.wanpinghui.wphlibrary.common.RxEventType;
import com.yunshl.yunshllibrary.rxbus.RxBus;
import com.yunshl.yunshllibrary.rxbus.SubscriptionBean;
import com.yunshl.yunshllibrary.utils.SystemUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.common.util.DensityUtil;
import org.xutils.x;

import retrofit.callback.FailOrExceptionType;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/11/21
 ***/

public abstract class BaseActivity extends AppCompatActivity implements GrobalListener {
    public static final int REQUEST_LOGIN = 2222;
    protected CompositeSubscription mSubscriptions;
    private TopWarningTextView textView;

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    /**
     * set status bar translucency
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static void setTranslucentStatus(Activity activity, boolean on) {
        Window win = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            if (on) {
                winParams.flags |= bits;
            } else {
                winParams.flags &= ~bits;
            }
            win.setAttributes(winParams);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (this instanceof StartActivity && ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0)) {
            finish();
            return;
        }
        x.view().inject(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        setStatus();
        initViews();

        setStatusBarColor();

        addWarningView();
        bindEvents();
        initData();
    }

    protected void setStatusBarColor() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                StatusBarCompat.setStatusBarColor(this, Color.WHITE, true);
            } else {
                if (SystemUtil.checkIsMeizuRom() || SystemUtil.isMIUI()) {
                    StatusBarCompat.setStatusBarColor(this, Color.WHITE, true);
                } else {
                    StatusBarCompat.setLightStatusBar(getWindow(), false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addWarningView() {
        View view = LayoutInflater.from(this).inflate(R.layout.view_top_warning_text, null);
        textView = (TopWarningTextView) view.findViewById(R.id.tv_warning_text);
        textView.setVisibility(View.GONE);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dip2px(23));
        if (this instanceof HomePageActivity) {
            layoutParams.topMargin = DensityUtil.dip2px(64f);
        } else {
            layoutParams.topMargin = DensityUtil.dip2px(44f);
        }
        addContentView(view, layoutParams);
    }

    public void setStatus() {
        setTranslucentStatus(this, isBar());
    }

    /**
     * 返回页面名称，用于页面统计分析
     *
     * @return
     */
    public abstract String getName();

    public abstract boolean isBar();

    public abstract void initViews();

    public abstract void bindEvents();

    public abstract void initData();

    public void refreshData() {
    }

    public boolean isHideBoa() {
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSub();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WPHSdk.addGrobalListener(this);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    protected void addSubscription(Subscription sb) {
        if (mSubscriptions == null) {
            mSubscriptions = new CompositeSubscription();
        }
        mSubscriptions.add(sb);
    }

    protected synchronized void unSub() {
        if (mSubscriptions != null && !mSubscriptions.isUnsubscribed()) {
            mSubscriptions.unsubscribe();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LOGIN && resultCode == RESULT_OK) {
            refreshData();
        }
    }

    @Override
    public void requestFial(int type, int code) {
        if (type == FailOrExceptionType.NO_LOGIN) {
            NimManager.getInstance().logout();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
    }

    @Override
    public void networkLost() {


    }

    @Override
    public void networkAvailable() {

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isHideBoa()) {
                View v = getCurrentFocus();
                //如果不是落在EditText区域，则需要关闭输入法
                if (HideKeyboard(v, ev)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    if (v instanceof EditText) {
                        v.clearFocus();
                    }
                    RxBus.getInstance().send(SubscriptionBean.createSendBean(RxEventType.TYPE_HIDE_KEYBOARD,null));
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private static boolean HideKeyboard(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {
            int[] location = {0, 0};
            view.getLocationInWindow(location);
            //获取现在拥有焦点的控件view的位置，即EditText
            int left = location[0], top = location[1], bottom = top + view.getHeight(), right = left + view.getWidth();
            //判断我们手指点击的区域是否落在EditText上面，如果不是，则返回true，否则返回false
            boolean isInEt = (event.getX() > left && event.getX() < right && event.getY() > top
                    && event.getY() < bottom);
            return !isInEt;
        }
        return false;
    }

    public void showWarningText(String text) {
        textView.setBackgroundResource(R.color.colorBgWarningText);
        if (textView != null) {
            if (TextUtil.isNotEmpty(text)) {
                textView.setText(text);
                textView.show();
            } else {
                textView.setVisibility(View.INVISIBLE);
            }
        }
    }

    public void showWarningText(String text, int backGround) {
        if (backGround != 0) {
            textView.setBackgroundColor(backGround);
        }
        if (textView != null) {
            if (TextUtil.isNotEmpty(text)) {
                textView.setText(text);
                textView.show();
            } else {
                textView.setVisibility(View.INVISIBLE);
            }
        }
    }

}
